<?php
/*********************************************************************************
* Filename: create_league.php
* 
* This PHP script validates input recieved from the user for creating a league,
* sends out email notifications, and if the input is valid inserts a new entry into
* the LEAGUES table in the database.
*
* Author: Caleb Goff
* Date Created: 10/10/2009
**********************************************************************************/

//Include common.php to utilize common functions and global variables
include_once 'common.php';
require_once "Mail.php";

//Retrieve variables from HTTP POST
$league_name      = $_REQUEST['leagueName'];
$league_pwd       = $_REQUEST['leaguePwd'];
$league_pwd_hash  = $_REQUEST['leaguePwdHash'];
$draft_type  	  = $_REQUEST['draftType'];
$draft_date  	  = $_REQUEST['draftDate'];
$emails     	  = $_REQUEST['emails'];

// Set the draft type as a boolean
if ($draft_type == "Random")
	$draft_type = 0;
else
	$draft_type = 1;

// The body of the invite emails sent to the list of emails specified by the user
$body = "Hello,\n
         You have been invited to join a Fantasy Broomball League by a friend. In order to create your 
	 team you will need to follow the link below:\n
	 $g_server/team_creation.php\n
	 You will need the following information:
         League Name: '$league_name'
	 League Password: '$league_pwd'\n
	 Your league commissioner has selected the following date for the live draft: $draft_date. If you cannot attend, 
	 the system will perform an automatic random draft for your team.\n
         If you feel you have recieved this email in error, please delete it. You will not be contacted by us again.\n
         Good luck!
         - The Fantasy Broomball Team";

//Query the database to check if that team name exists
//for that league already, and throw an error if it does.
$query  = "SELECT LEAGUE_NAME FROM LEAGUES";
$result = do_query($query, $g_db_name, $g_username);

$i = 0;
$retVal = 0;

while($row = mysql_fetch_assoc($result)){
	$name = $row['LEAGUE_NAME'];

	// Check if the name exists in the database
	// already and return a proper error code
	if ($name == $league_name){
		$retVal = 1;
		break;
	}
}

//Check if league was found to exist already
//If not, insert the league into the database
if ($retVal == 0){
	$time = strtotime($draft_date);
	$date =	date('Y-m-d',$time);
	$query = "INSERT INTO LEAGUES (LEAGUE_NAME, LEAGUE_PWD, DRAFT, DRAFT_DATE) 
		      VALUES('$league_name','$league_pwd_hash','$draft_type','$date')";
	do_query($query, $g_db_name, $g_username);
	email_message($league_invite_subject,$body,$emails);
}

//Return value to caller to let them know whether the team was added or not
echo $retVal;

?>

